# -*- coding: utf-8 -*-
# Date: 2025-01-02
# Author: HonestQiao
#
# Desc: 行空板K10天气牌

import utime
import uos
import json

from machine import SoftI2C, Pin
import xl9535_relay
from ahtx0 import AHT20

from do_connect import do_connect
from weather import get_weather

from gui.core.writer import Writer, CWriter
from gui.core.nanogui import refresh
from gui.core.colors import *
from gui.widgets.label import *

from color_setup import ssd  # Create a display instance

# 配置信息
from weather_config import *

# 关闭声音
pin1 = Pin(38, Pin.OUT)
pin2 = Pin(0, Pin.OUT)
pin3 = Pin(45, Pin.OUT)
pin1.value(False)
pin2.value(False)
pin3.value(False)

# 初始化温湿度传感器
i2c = SoftI2C(scl=Pin(48), sda=Pin(47),freq=400000)
aht = AHT20(i2c)

# 初始化EXT_GPIO，点亮屏幕
board = xl9535_relay.XL9535_KXV5(i2c, 0x20)
board.init()
board.relays(0x0000)
board.relay(0, False)
board.relay(0, True)

# K10设置
ssd._wcd(b'\x36', int.to_bytes(0x88, 1, 'little'))

# 填充背景颜色
ssd.fill(BG_COLOR)

# 刷新屏幕
refresh(ssd, True)  # Initialise and clear display.

# 字体文件调用
import gui.fonts.freesans20 as font20
import gui.fonts.font6 as font6
import gui.fonts.freesans_6_char as font6_char
import gui.fonts.puhui_m_12_all as font_cn
import gui.fonts.puhui_m_32_char as font_char

# 屏幕元素
CWriter.set_textpos(ssd, 0, 0)  # In case previous tests have altered it
wri = CWriter(ssd, font_cn, WHITE, BG_COLOR)  # Report on fast mode. Or use verbose=False
wri.set_clip(True, True, False)

wri1 = CWriter(ssd, font_cn, GREEN, BG_COLOR)  # Report on fast mode. Or use verbose=False
wri1.set_clip(True, True, False)

wri2 = CWriter(ssd, font6_char, GREEN, BG_COLOR)  # Report on fast mode. Or use verbose=False
wri2.set_clip(True, True, False)

wri3 = CWriter(ssd, font_char, RED, BG_COLOR)  # Report on fast mode. Or use verbose=False
wri3.set_clip(True, True, False)

# 温度
lbs = {}
lbs['城市图片'] = Label(wri, 5, 5, " ")
lbs['城市名称'] = Label(wri, 5, 15, "城市")

lbs['报告时间'] = (
    Label(wri, 5, 80, "某月某日"),
    Label(wri, 5, 140, "星期几"),
    Label(wri, 5, 180, "00:00:00"),
    Label(wri, 25, 180, "00:00发布")
)

y1 = 25

ssd.rect(5, y1-3, 110, y1 + 35, YELLOW)

lbs['温度B'] = Label(wri3, y1+10, 15, " ")
lbs['温度'] = Label(wri3, y1+10, 25, "?")
lbs['温度单位'] = Label(wri2, y1, 55, "°C")

#lbs['天气图标'] = Label(wri, y1+20, 55, "晴")
lbs['天气类型'] = Label(wri, y1+20, 55, "*")
lbs['温度范围'] = Label(wri2, y1+40, 55, "低~高°C")

lbs['风向'] = Label(wri, y1+20, 150, "风向")
lbs['风力'] = Label(wri, y1+20, 200, "风力")
lbs['空气质量'] = Label(wri, y1+40, 180, "空气质量")

try:
    temperature = aht.temperature + TEMPERATURE_DIFF
    relative_humidity = aht.relative_humidity + RELATIVE_HUMIDITY_DIFF
except Exception as e:
    print(e)
    temperature = 0
    relative_humidity = 0

y1 = 90
lbs['环境温度'] = (
    Label(wri, y1, 10, "环境温度:"),
    Label(wri2, y1, 70, "%d°C" % temperature)
)
lbs['环境湿度'] = (
    Label(wri, y1, 120, "环境湿度:"),
    Label(wri2, y1, 180, "%d%%" % relative_humidity)
)


lbs['列表'] = {}
y1 = 120
y2 = 136

ssd.line(0, y1 - 5, ssd.width - 1, y1 - 5, YELLOW)

lbs['列表']['湿度'] = (
    Label(wri, y2, 10, "湿度"),
    Label(wri2, y1, 10, "%d%%" % relative_humidity)
)

lbs['列表']['大气压'] = (
    Label(wri, y2, 65, "大气压"),
    Label(wri2, y1, 65-15, "****hPa")
)

lbs['列表']['能见度'] = (
    Label(wri, y2, 120, "能见度"),
    Label(wri2, y1, 120, "**.*KM")
)

lbs['列表']['紫外线强度'] = (
    Label(wri, y2, 175, "紫外线"),
    Label(wri, y2+12, 175, "强度"),
    Label(wri1, y1, 185, "**")
)

y1 = 170-5
y2 = 186-5

lbs['列表']['体感温度'] = (
    Label(wri, y2, 10, "体感", align=ALIGN_CENTER),
    Label(wri, y2+12, 10, "温度", align=ALIGN_CENTER),
    Label(wri2, y1, 10, "**°C", align=ALIGN_CENTER)
)

lbs['列表']['风力'] = (
    Label(wri, y2, 65, "风力", align=ALIGN_CENTER),
    Label(wri1, y1, 65, "*级", align=ALIGN_CENTER)
)

lbs['列表']['风向'] = (
    Label(wri, y2, 120, "风向", align=ALIGN_CENTER),
    Label(wri1, y1, 120, "**风", align=ALIGN_CENTER)
)

lbs['列表']['降水量'] = (
    Label(wri, y2, 175, "降水量", align=ALIGN_CENTER),
    Label(wri2, y1, 175, "*.**mm", align=ALIGN_CENTER)
)


lbs['生活指数'] = {}
y1 = 220
y2 = 236

ssd.line(0, y1 - 5, ssd.width - 1, y1 - 5, YELLOW)


lbs['生活指数']['限行指数'] = (
    Label(wri, y2, 10, "限行", align=ALIGN_CENTER),
    Label(wri, y2+12, 10, "尾号", align=ALIGN_CENTER),
    Label(wri1, y1, 10, "* *", align=ALIGN_CENTER)
)

lbs['生活指数']['穿衣指数'] = (
    Label(wri, y2, 65, "穿衣", align=ALIGN_CENTER),
    Label(wri, y2+12, 65, "指数", align=ALIGN_CENTER),
    Label(wri1, y1, 65, "*", align=ALIGN_CENTER)
)

lbs['生活指数']['紫外线强度指数'] = (
    Label(wri, y2, 120, "紫外线", align=ALIGN_CENTER),
    Label(wri, y2+12, 120, "强度", align=ALIGN_CENTER),
    Label(wri1, y1, 120, "*", align=ALIGN_CENTER)
)

lbs['生活指数']['舒适度指数'] = (
    Label(wri, y2, 175, "舒适度", align=ALIGN_CENTER),
    Label(wri, y2+12, 175, "指数", align=ALIGN_CENTER),
    Label(wri1, y1, 175, "****", align=ALIGN_CENTER)
)

y1 = 270
y2 = 286
lbs['生活指数']['洗车指数'] = (
    Label(wri, y2, 10, "洗车", align=ALIGN_CENTER),
    Label(wri, y2+12, 10, "指数", align=ALIGN_CENTER),
    Label(wri1, y1, 10, "***", align=ALIGN_CENTER)
)

lbs['生活指数']['运动指数'] = (
    Label(wri, y2, 65, "运动", align=ALIGN_CENTER),
    Label(wri, y2+12, 65, "指数", align=ALIGN_CENTER),
    Label(wri1, y1, 65, "***", align=ALIGN_CENTER)
)

lbs['生活指数']['感冒指数'] = (
    Label(wri, y2, 120, "感冒", align=ALIGN_CENTER),
    Label(wri, y2+12, 120, "指数", align=ALIGN_CENTER),
    Label(wri1, y1, 120, "***", align=ALIGN_CENTER)
)

lbs['生活指数']['晾晒指数'] = (
    Label(wri, y2, 175, "晾晒", align=ALIGN_CENTER),
    Label(wri, y2+12, 175, "指数", align=ALIGN_CENTER),
    Label(wri1, y1, 175, "****", align=ALIGN_CENTER)
)
refresh(ssd)

city_id = CITY_ID
do_connect(SSID_NAME, SSID_PASSWD)

counter = 0
while True:
    # 获取当前时间
    current_time = utime.localtime()
    
    lbs['报告时间'][2].value(f'{"%02d" % current_time[3]}:{"%02d" % current_time[4]}:{"%02d" % current_time[5]}')

    if not counter % 300 == 0:
        counter += 1
        refresh(ssd)
        utime.sleep(1)

        continue
    else:
        counter = 1

    print("请求最新天气信息：")
    
    try:
        showData = get_weather(city_id)
        print(json.dumps(showData))

        #lbs['城市图片'].value(showData['城市图片'])
        lbs['城市名称'].value(showData['城市名称'])

        lbs['报告时间'][0].value(showData['报告时间'][0])
        lbs['报告时间'][1].value(showData['报告时间'][1])
        #lbs['报告时间'][2].value(f'{"%02d" % current_time[3]}:{"%02d" % current_time[4]}:{"%02d" % current_time[5]}')
        lbs['报告时间'][3].value("%s发布" % showData['报告时间'][2])

        temperature = int(showData['温度'])
        lbs['温度B'].value('-' if temperature < 0 else '')
        lbs['温度'].value(str(-temperature if temperature < 0 else temperature))
        #lbs['温度单位'].value("°C")

        #lbs['天气图标'].value(showData['天气图标'])
        lbs['天气类型'].value(showData['天气类型'])
        lbs['温度范围'].value(showData['温度范围'])

        lbs['风向'].value(showData['风向'])
        lbs['风力'].value(showData['风力'])
        lbs['空气质量'].value(showData['空气质量'])

        try:
            temperature = aht.temperature + TEMPERATURE_DIFF
            relative_humidity = aht.relative_humidity + RELATIVE_HUMIDITY_DIFF
        except Exception as e:
            print(e)
            temperature = 0
            relative_humidity = 0

        lbs['环境温度'][-1].value("%d°C" % temperature)
        lbs['环境湿度'][-1].value("%d%%" % relative_humidity)


        lbs['列表']['湿度'][-1].value("%s%s" % (showData['列表']['湿度']['value'],showData['列表']['湿度']['unit']))

        lbs['列表']['大气压'][-1].value("%s%s" % (showData['列表']['大气压']['value'],showData['列表']['大气压']['unit']))

        lbs['列表']['能见度'][-1].value("%s%s" % (showData['列表']['能见度']['value'],showData['列表']['能见度']['unit']))

        lbs['列表']['紫外线强度'][-1].value("%s%s" % (showData['列表']['紫外线强度']['value'],showData['列表']['紫外线强度']['unit']))

        
        lbs['列表']['体感温度'][-1].value("%s%s" % (showData['列表']['体感温度']['value'],showData['列表']['体感温度']['unit']))

        lbs['列表']['风力'][-1].value("%s%s" % (showData['列表']['风力']['value'],showData['列表']['风力']['unit']))

        lbs['列表']['风向'][-1].value("%s%s" % (showData['列表']['风向']['value'],showData['列表']['风向']['unit']))

        lbs['列表']['降水量'][-1].value("%0.2f%s" % (showData['列表']['降水量']['value'],showData['列表']['降水量']['unit']))


        lbs['生活指数']['限行指数'][-1].value(showData['生活指数'][0]['index_level'])

        lbs['生活指数']['穿衣指数'][-1].value(showData['生活指数'][1]['index_level'])

        lbs['生活指数']['紫外线强度指数'][-1].value(showData['生活指数'][2]['index_level'])

        lbs['生活指数']['舒适度指数'][-1].value(showData['生活指数'][3]['index_level'])


        lbs['生活指数']['洗车指数'][-1].value(showData['生活指数'][4]['index_level'])

        lbs['生活指数']['运动指数'][-1].value(showData['生活指数'][5]['index_level'])

        lbs['生活指数']['感冒指数'][-1].value(showData['生活指数'][6]['index_level'])

        lbs['生活指数']['晾晒指数'][-1].value(showData['生活指数'][7]['index_level'])
    
    except Exception as e:
        print(e)

    refresh(ssd)